<template>
	<view>
		<view class="calendarComponent_box">
			<!-- 月份 -->
			<view class="calendarMonth_con">
				<view class="monthBtn" @click="daysPre">
					<template v-if="weekMode">上一周</template>
					<template v-else>上一月</template>
				</view>
				<view class="monthCon" @click="yearMonthClick">
					<text>{{currentYear}}-{{currentMonth}}</text>
				</view>
				<view class="monthBtn" @click="daysNext">
					<template v-if="weekMode">下一周</template>
					<template v-else>下一月</template>
				</view>
			</view>

			<!-- 日历 -->
			<view class="calendarDay_box">
				<!-- 周 -->
				<view class="calendarWeek_con">
					<view class="weekItem" v-for="(week, index) in weeks" :key="index">
						{{week}}
					</view>
				</view>

				<!-- 日期 -->
				<view class="calendarDay_con">
					<swiper class="swiperList" :style="{ width: '100%', height: sheight}" :indicator-dots="false"
						:autoplay="false" :duration="duration" :current="current" :circular="true"
						@change="swiperChange">
						<swiper-item class="swiperItem" v-for="sitem in swiper" :key="sitem">
							<view class="dayList_con">
								<template v-if="sitem === current">
									<view class="dayItem" v-for="(item,index) in days" :key="index" :class="{
									'dayHidden': !item.show
								}" @click="dayClick(item)">
										<button hover-class="none" class="date"
											:class="[
										item.fullDate === selectedDate ? 'isCheckedBg' : '', item.record ? 'isChecked' : '', item.isBao ? 'isChecked' : '', item.isOver=='1' ? 'isChecked' : '', item.borrow ? 'isChecked' : '', item.note ? 'isChecked' : '']"
											:disabled="item.disabled">
											<view class="solar">
												<text class="dotToday" v-if="item.isToday">今</text>
												<text v-else>{{item.time.getDate()}}</text>
											</view>
											<view class="dotRecord">{{item.record}}</view>
											<view class="dotBao" v-if="item.isBao && defaultWorksite.role>1"></view>
											<view class="dotOver" v-if="item.isOver=='1'"></view>
											<view class="dotBorrow" v-if="item.borrow && defaultWorksite.role>2"></view>
											<view class="dotBorrow2" v-if="item.borrow && defaultWorksite.role=='1'">{{item.borrow}}</view>
											<view class="dotNote" v-if="item.note"></view>
										</button>
									</view>
								</template>

							</view>
						</swiper-item>
					</swiper>
				</view>

				
			</view>

			<!-- 偏差提示 -->
			<view class="calendar-error" v-if="error"  @click="errorClick">
				<text>您的记工数据与工人记工数据有偏差，立即查看</text>
				<u-icon name="arrow-right" color="#999" size="32"></u-icon>
			</view>
		</view>

		<!-- 选择年月弹窗 -->
		<u-popup v-model="yearMonthShow" mode="center" border-radius="20" safe-area-inset-bottom closeable close-icon-size="40" safe-area-inset-bottom>
			<view class="yearMonth_box">
				<view class="yearMonth_head">
					<u-section title="选择年月" font-size="32" line-color="#327FE8" :right="false"></u-section>
				</view>
				<view class="yearList_con">
					<u-tabs :show-bar="false" active-color="#327FE8" :list="yearList" :current="yearIndex" height="100"
						font-size="32" @change="yearChange">
					</u-tabs>
				</view>
				<view class="monthList_con">
					<view class="monthItem" :class="monthIndex == index ? 'active':''" v-for="(item,index) in monthList"
						:key="index" @click="monthClick(index)">
						{{item.name}}
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		gegerateDates,
		dateEqual,
		formatDate
	} from '@/util/generateDates.js';
	export default {
		props: {
			duration: {
				type: Number,
				default: 500
			},
			// 打卡记录
			dotList: {
				type: Array,
				default () {
					return []
				}
			},
			// 偏差
			error: {
				type: Boolean,
				default: false
			},
			// 父组件页面名称
			parent: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				weeks: ['一', '二', '三', '四', '五', '六', '日'],
				current: 1,
				currentYear: '',
				currentMonth: '',
				currentDate: '',

				weekMode: false, // 周模式、月模式
				swiper: [0, 1, 2],

				// 选择的日期
				selectedDate: formatDate(new Date(), 'yyyy-MM-dd'), //默认今天

				// 生成日期数据
				days: [],

				// 年月弹窗
				yearMonthShow: false,
				yearList: JSON.parse(uni.getStorageSync('yearList')),
				monthList: JSON.parse(uni.getStorageSync('monthList')),
				yearIndex: 0,
				monthIndex: 0,
				
				defaultWorksite: JSON.parse(uni.getStorageSync('defaultWorksite')),
				
				//initDate:[],
			};
		},
		created() {
			// var _this = this;
			// setTimeout(function() {
			// 	_this.initDate();
			// }, 1000)
		},
		mounted() {
			console.log('每次进入是否更新')
			console.log(this.dotList)
		},
		watch: {
			
			// 日历标记
			dotList: function(newvalue) {
				console.log("==watch监听日历标记==")
				const days = this.days.slice(0);
				newvalue.forEach(item => {
					const index = days.findIndex(ditem => ditem.fullDate === item.date);

					if (index > -1) {
						days[index].info = item;
					}
				});
				this.days = days;
				// console.log('每次进入是否更1新')
				// console.log(this.dotList)
				// this.dotList=this.dotList;
				// this.$forceUpdate();
				
				
				//这个地方不能放开苹果兼容有问题
				//this.initDate(this.currentYear+'-'+this.currentMonth+'-'+this.currentDate);
			}
		},
		methods: {
			/**
			 * 日历 start
			 */
			// 选择年月 picker
			// monthChange(e) {
			// 	// console.log(e);
			// 	var month = e.detail.value;
			// 	console.log('选择的年月：' + month);
			// 	var arr = month.split('-');
			// 	// console.log(arr)
			// 	this.currentYear = arr[0];
			// 	this.currentMonth = arr[1];
			// 	const d = new Date(this.currentYear, this.currentMonth - 1, 1);
			// 	this.initDate(d);
			// },
			yearMonthClick() {
				this.yearMonthShow = true;
			},

			// 选择年
			yearChange(index) {
				// console.log("==年索引==");
				// console.log(index);
				var _this = this;
				_this.yearIndex = index;
				_this.monthIndex = '-1';
			},

			// 选择月
			monthClick(index) {
				// console.log("==月索引==");
				// console.log(index);
				var _this = this;
				_this.monthIndex = index;
				_this.yearMonthShow = false;

				var currentYear = parseInt(_this.yearList[_this.yearIndex].year);
				var currentMonth = parseInt(_this.monthList[_this.monthIndex].month);

				console.log("==选择的年月==");
				console.log(currentYear, currentMonth)
				const d = new Date(currentYear, currentMonth - 1, 1);
				// console.log(d);

				// 初始化日历
				_this.initDate(d);

				// 调用父组件数据刷新
				_this.updateParent();
			},

			// 初始化日历的方法
			initDate(cur) {
				// console.log(cur)
				var _this = this;
				let date = '';
				if (cur) {
					date = new Date(cur)
				} else {
					date = new Date()
				}
				_this.currentDate = date.getDate() // 今日日期 几号
				_this.currentYear = date.getFullYear() // 当前年份
				var currentMonth = date.getMonth() + 1 // 当前月份
				_this.currentMonth = currentMonth > 9 ? currentMonth : '0' + currentMonth; // 月份补0
				_this.currentWeek = date.getDay() === 0 ? 7 : date.getDay() // 1...6,0   // 星期几
				const nowY = new Date().getFullYear() // 当前年份
				const nowM = new Date().getMonth() + 1
				const nowD = new Date().getDate() // 今日日期 几号

				let days = [];
				if (_this.weekMode) {
					days = gegerateDates(date, 'week');
				} else {
					days = gegerateDates(date, 'month');
				}

				days.forEach(day => {
					const dot = _this.dotList.find(item => {
						return dateEqual(item.date, day.fullDate);
					})
					if (dot) {
						day.record = dot.record;
						day.note = dot.note;
						day.borrow = dot.borrow;
						day.isBao = dot.isBao;
						day.isOver = dot.isOver;
					}
				})
				console.log(days)
				_this.days = days;

				//  派发事件,时间发生改变
				let obj = {
					start: '',
					end: ''
				};
				if (_this.weekMode) {
					obj.start = _this.days[0].time;
					obj.end = _this.days[6].time
				} else {
					const start = new Date(_this.currentYear, _this.currentMonth - 1, 1);
					const end = new Date(_this.currentYear, _this.currentMonth, 0);
					obj.start = start;
					obj.end = end;
				}
				_this.$emit('days-change', obj);

				// 更新选中年
				for (var i = 0; i < _this.yearList.length; i++) {
					if (_this.yearList[i].year == _this.currentYear) {
						_this.yearIndex = i;
					}
				}

				// 更新选中月
				for (var i = 0; i < _this.monthList.length; i++) {
					if (_this.monthList[i].month == _this.currentMonth) {
						_this.monthIndex = i;
					}
				}

				// 给父组件传递年月
				_this.$emit('year', _this.currentYear);
				_this.$emit('month', _this.currentMonth);
				_this.$emit('day', _this.currentDate);
				_this.$emit('weekMode', _this.weekMode);
			},

			// 左右滑动
			swiperChange(e) {
				// console.log(e);
				var _this = this;
				const pre = _this.current;
				const current = e.target.current;
				/* 根据前一个减去目前的值我们可以判断是下一个月/周还是上一个月/周 
				 * current - pre === 1, -2时是下一个月/周
				 * current - pre === -1, 2时是上一个月/周
				 */
				_this.current = current;
				if (current - pre === 1 || current - pre === -2) {
					_this.daysNext();
				} else {
					_this.daysPre();
				}
			},

			// 上一个
			daysPre() {
				var _this = this;
				if (_this.weekMode) {
					const d = new Date(_this.currentYear, _this.currentMonth - 1, _this.currentDate);
					d.setDate(d.getDate() - 7);
					_this.initDate(d);
				} else {
					const d = new Date(_this.currentYear, _this.currentMonth - 2, 1);
					_this.initDate(d);
				}

				// 调用父组件数据刷新
				_this.updateParent();
			},

			// 下一个
			daysNext() {
				var _this = this;
				if (_this.weekMode) {
					const d = new Date(_this.currentYear, _this.currentMonth - 1, _this.currentDate);
					d.setDate(d.getDate() + 7);
					_this.initDate(d);
				} else {
					const d = new Date(_this.currentYear, _this.currentMonth, 1);
					_this.initDate(d);
				}

				// 调用父组件数据刷新
				_this.updateParent();
			},

			// 展开or收起
			changeMode() {
				const premode = this.weekMode;
				let isweek = false;
				if (premode) {
					isweek = !!this.days.find(item => item.fullDate === this.selectedDate)
				}
				this.weekMode = !this.weekMode;
				let d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate)
				const sel = new Date(this.selectedDate.replace('-', '/').replace('-', '/'));
				const isMonth = sel.getFullYear() === this.currentYear && (sel.getMonth() + 1) === this.currentMonth;
				if ((this.selectedDate && isMonth) || isweek) {
					d = new Date(this.selectedDate.replace('-', '/').replace('-', '/'))
				}
				this.initDate(d)
			},

			// 点击日期
			dayClick(e) {
				// console.log(e);
				this.selectedDate = e.fullDate;
				this.$emit('selected-change', e);
			},

			// 调用父组件数据刷新
			updateParent() {
				var _this = this;

				// 记工首页
				if (_this.parent == 'keepHome') {
					_this.$parent.getDotList();
				}

				// 工人详情数据更新
				if (_this.parent == 'workerDetail') {
					_this.$parent.getWorkerStatistics();
					_this.$parent.getWorkerCompare();
				}
				
				// 工资单
				if (_this.parent == 'wageHome') {
					_this.$parent.getDotList();
				}

				// 老板工地简报
				if (_this.parent == 'bulletinHome') {
					_this.$parent.getBulletinStatistics();
					_this.$parent.getDotList();
				}
			},

			// 记账异常
			errorClick() {
				uni.navigateTo({
					url: '/pages/dataError/dataError?type=1'
				})
			},
		},
		computed: {
			// 计算高度
			sheight() {
				// 根据年月判断有多少行
				// 判断该月有多少天
				let h = '110rpx';
				if (!this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth, 0);
					const days = d.getDate(); // 判断本月有多少天
					let day = new Date(d.setDate(1)).getDay();
					if (day === 0) {
						day = 7;
					}
					const pre = 8 - day;
					const rows = Math.ceil((days - pre) / 7) + 1;
					h = 110 * rows + 'rpx'
				}
				return h
			},
			predays() {
				let pres = [];
				if (this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate)
					d.setDate(d.getDate() - 7);
					pres = gegerateDates(d, 'week')
				} else {
					const d = new Date(this.currentYear, this.currentMonth - 2, 1)
					pres = gegerateDates(d, 'month')
				}
				return pres;
			},
			nextdays() {
				let nexts = [];
				if (this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate)
					d.setDate(d.getDate() + 7);
					nexts = gegerateDates(d, 'week')
				} else {
					const d = new Date(this.currentYear, this.currentMonth, 1)
					nexts = gegerateDates(d, 'month')
				}
				return nexts;
			}
		}
	}
</script>

<style scoped lang="scss">
	.calendarComponent_box {
		width: 100%;
	}

	/* 月份 */
	.calendarMonth_con {
		height: 90rpx;
		padding: 0 60rpx;
		background: #f0f0f0;
		overflow: hidden;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.monthBtn {
		font-size: 28rpx;
		color: $uni-color;
	}

	.monthCon {
		width: 340rpx;
		height: 0;
		color: $uni-color;
		border-bottom: 90rpx solid #fff;
		border-left: 15rpx solid transparent;
		border-right: 15rpx solid transparent;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		position: relative;
	}

	.monthCon text {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		position: absolute;
		left: 0;
		right: 0;
		top: 30rpx;
	}

	// 日历
	.calendarDay_box {
		background-color: $uni-color-white;
	}

	.calendarWeek_con {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		justify-content: center;
		align-items: center;
		display: flex;
		flex-wrap: wrap;
	}

	.weekItem {
		width: calc(100% / 7);
		height: 100%;
		text-align: center;
		font-size: 30rpx;
		color: #666;
	}

	.calendarDay_con {
		min-height: 60rpx;
	}

	.swiperList {
		width: 100%;
		transition: height ease-out 0.3s;
	}

	.swiperItem {
		margin: 0;
		padding: 0;
		height: 100%;
	}

	.dayList_con {
		width: 100%;
		height: 100%;
		overflow: hidden;
		display: flex;
		flex-wrap: wrap;
	}

	.dayItem {
		width: calc(100% / 7);
		height: 100rpx;
		text-align: center;
		margin-bottom: 10rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.dayItem:nth-child(7n) {
		margin-right: 0rpx;
	}

	.dayHidden {
		visibility: hidden;
	}

	.date {
		width: 86rpx;
		height: 100rpx;
		font-size: 28rpx;
		font-weight: bold;
		color: $uni-color;
		text-align: center;
		border-radius: 10rpx;
		border: 2rpx solid #fff;
		box-sizing: border-box;
		overflow: hidden;
		margin: 0 auto;
		position: relative;
	}

	.date[disabled] {
		color: #ccc;
		background: transparent;
	}

	/* 选中style */
	.isChecked {
		// border: 2rpx solid #CCE0FF;
		// background-color: #f0f6ff;
	}
	
	.isCheckedBg {
		border: 2rpx solid #ffe4cd;
		background-color: #fff3e2;
	}

	.dotToday {
		color: $uni-color-active;
		font-size: 24rpx;
	}

	.dotRecord {
		height: 28rpx;
		text-align: center;
		font-size: 22rpx;
		font-weight: normal;
		color: $uni-color-active;
	}

	// 包
	.dotBao::before {
		content: '包';
		width: 28rpx;
		height: 28rpx;
		font-size: 18rpx;
		color: #fff;
		position: absolute;
		bottom: 0;
		left: 0;
		z-index: 10;
	}

	.dotBao::after {
		content: '';
		width: 28rpx;
		height: 28rpx;
		text-align: center;
		background: rebeccapurple;
		border-top-right-radius: 10rpx;
		border-bottom-left-radius: 10rpx;
		overflow: hidden;
		position: absolute;
		bottom: 0;
		left: 0;
		z-index: 0;
	}

	// 加
	.dotOver::before {
		content: '加';
		width: 28rpx;
		height: 28rpx;
		font-size: 18rpx;
		color: #fff;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
	}

	.dotOver::after {
		content: '';
		width: 28rpx;
		height: 28rpx;
		text-align: center;
		background: #06C158;
		border-top-left-radius: 10rpx;
		border-bottom-right-radius: 10rpx;
		overflow: hidden;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 0;
	}
	.dotBorrow2{
		width: 100%;
		height: 28rpx;
		font-size: 18rpx;
		color: #f00;
		position: absolute;
		bottom: 0;
		left: 0;
		z-index: 100;
	}
	// 借
	.dotBorrow::before {
		content: '借';
		width: 28rpx;
		height: 28rpx;
		font-size: 18rpx;
		color: #fff;
		position: absolute;
		bottom: 0;
		right: 0;
		z-index: 10;
	}

	.dotBorrow::after {
		content: '';
		width: 28rpx;
		height: 28rpx;
		text-align: center;
		background: #ffc30b;
		border-top-left-radius: 10rpx;
		border-bottom-right-radius: 10rpx;
		overflow: hidden;
		position: absolute;
		bottom: 0;
		right: 0;
		z-index: 0;
	}

	// 备
	.dotNote::before {
		content: '备';
		width: 28rpx;
		height: 28rpx;
		font-size: 18rpx;
		color: #fff;
		position: absolute;
		top: 0;
		right: 0;
		z-index: 10;
	}

	.dotNote::after {
		content: '';
		width: 28rpx;
		height: 28rpx;
		text-align: center;
		background: green;
		border-top-right-radius: 10rpx;
		border-bottom-left-radius: 10rpx;
		overflow: hidden;
		position: absolute;
		top: 0;
		right: 0;
		z-index: 0;
	}

	/* 切换模式 */
	.calendarMode_con {
		padding-bottom: 30rpx;
		overflow: hidden;
	}

	.modeChange {
		padding-top: 10rpx;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modeChange text {
		font-size: 28rpx;
		color: #666;
		margin-right: 5rpx;
	}

	// 偏差提示
	.calendar-error {
		padding: 30rpx;
		background-color: #fff4e1;
		overflow: hidden;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.calendar-error text {
		color: #FF2C00;
		font-size: 28rpx;
	}

	/**
	 * 选择年月弹窗
	 */
	.yearMonth_box {
		width: 690rpx;
	}

	.yearMonth_head {
		padding: 30rpx 30rpx 0;
	}

	.yearMonth_box .yearList_con {
		border-bottom: 1rpx solid #dcdcdc;
		overflow: hidden
	}

	.yearMonth_box .monthList_con {
		padding: 30rpx;
		overflow: hidden;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: center;
	}

	.yearMonth_box .monthItem {
		width: 160rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		color: #333;
		// background: linear-gradient(0deg, #ffffff 0%, #ededed 100%);
		background-color: #F5F5F5;
		border-radius: 10rpx;
		// box-shadow: 1rpx 3rpx 5rpx 0 rgba(0, 0, 0, 0.16);
		margin-bottom: 30rpx;
	}

	.yearMonth_box .monthItem.active {
		color: $uni-color;
		background: uni-color-active;
	}
</style>
